import axios from 'axios'
import store from '../store'
import router from '../router'
import {Toast} from 'vant'

function httpRequest(url,data,method){
    var userInfo = store.state.userInfo;
    if(typeof userInfo == 'string'){
        userInfo = JSON.parse(userInfo)
    }
    if(store.state.token){
        axios.defaults.headers.token = store.state.token;
        axios.defaults.headers.userId = userInfo.id;
    }
    return new Promise ((resolve,reject) => {
        const option = {
            url,
            data,
            method
        }
        if(method == 'get'){
            option.params = data
        }else{
            option.data = data
        }

        axios(option).then(res => {
            if(res.data.status.statusCode === 0) {
                resolve(res)
            }else if(res.data.status.statusCode == '1895001') {
                router.replace({
                    path: '/Login',
                    query: {
                        name: router.currentRoute.fullPath
                    }
                })
            }else {
                Toast(res.data.status.statusReason)
                reject(res.data.status.statusReason)
            }
        }).catch(err => {
            Toast(err)
            reject(err);
        })
    })
}

export default httpRequest